/**
 * @author benny.zheng
 * @data 2016-06-06
 * @description 本文件用于方便复制粘贴UI模块之用，请更新这里的说明
 *              另外，考虑到一般是放在js/src/pages/page-name/main.js，因此使用../../
 *              如果不是这个目录，请更改成正确的相对路径
 */
//----------------require--------------


var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析
var wechat = require("../plugin/wx/wx-api");

var ajax = require("mlib/io/ajax");
var Confirm = require("../layer/confirm");
var Alert = require("../layer/alert");
var showMessage = require("../layer/info");
var closest = require("mlib/dom/closest");
var touch = require("mlib/evt/touch");
var quantity = require("../plugin/util/up-down");
var limitCharacts = require("../plugin/util/limit-characts");



module.exports = function(node, opts) {
    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null; 
	var m_quantity = null;
	var order_price = null; // 订单价格
	var expense_price = null; // 手续费
	var return_price = null; // 实退金额
	var other_reason = null;
	var m_reason = null;
    //-------------事件响应声明---------------
    var evtFuncs = {
            confirmSubmit:function(evt){
				if(nodeList.quantity.value==0){
					showMessage("\u8bf7\u9009\u62e9\u9000\u8ba2\u6570\u91cf");
					return ;
				}
				m_reason = custFuncs.getReason();
				if(m_reason.length==0){
				  showMessage("\u8bf7\u9009\u62e9\u9000\u8ba2\u539f\u56e0");
				  return ;
				}
              var input= nodeList.quantity,value=input.value,params ={};
			       params["reason"] = JSON.stringify(m_reason);
			       params["voucherid"] = data.voucherid;
			       params["ocid"] = data.ocid;
			       params["number"] = value;
				Confirm({
					content:"\u786e\u8ba4\u9000\u8ba2\uff1f",
					okFn:function(){
						var self =this;
						if(that.isLock()) {
							return;
						}
						that.lock();
						 ajax({
							 url: "/index.php?r=order/back&vouid="+data.voucherid+"&ocid="+data.ocid+"&number="+value,
							 data: params,
							 method: "post",
							onSuccess: function(res) {
								that.unLock();
								Alert(res.msg,{okFn:function(){
									if(res.status==1){						 
										 location.href = res.url;
									}
								}});    						
								
							},
							onError: function(xmlHttp) {
								that.unLock();
							}, // 当访问出错，比如网络连接不上、解析内容失败时触发，超时也会触发
							onTimeout: function(xmlHttp) { }, // 超时触发
							 onAbort: function() {} // 网络中断时触发
						 });			
					}
				});  

			},	
			modifyNum:function(result){ // 点击数量加减更新商品总金额                  
				 var obj=result.data,
					 input=obj.input,
					 theval =input.value;
					 order_price = parseInt(theval) * parseFloat(data.orderprice);
					 if(data.etype==1){
						 expense_price = order_price * parseFloat(data.expense) * parseInt(theval);
					 }else if(data.etype==2){
						 expense_price = parseInt(theval) * parseFloat(data.expense); 
					 }
					 return_price = order_price - data.discountedamount;// 实退款 = （单价*退订数量-优惠金额【和数量无关】）
					 custFuncs.updateprice();
			},			
			reason:function(evt){
				var target=closest(evt.target,".reason-item"),id=target.dataset.id;
				target.classList.toggle("reason-item-checked");
				if(id=="0"){
					if(target.classList.contains("reason-item-checked")){
						nodeList.otherbox.style.display = 'block';
					}else{
						nodeList.otherbox.style.display = 'none';
					}					
				}				
			}

	}

    //-------------子模块实例化---------------
    var initMod = function() {
		m_quantity = quantity(nodeList.ticketlist,{});
        order_price = data.orderprice*data.minallowback;   
		limitCharacts([nodeList.otherreason],60,true);
		wechat('off').init();
    }

    //-------------绑定事件------------------
    var bindEvents = function() {
		  touch.on(nodeList.submit,"tap",evtFuncs.confirmSubmit);
		  touch.on(nodeList.reasonlist,"tap",".reason-item",evtFuncs.reason);
		  m_quantity.bind("inputChange", evtFuncs.modifyNum);
				
	}

    //-------------自定义函数----------------
    var custFuncs = {
         getReason:function(){
			 var reasons = nodeList.reasonlist.querySelectorAll(".reason-item"),checkedReasons = [];
			 [].slice.call(reasons).forEach(function(item,index){
				 if(item.classList.contains("reason-item-checked")){
					 var itemid= item.dataset.id,itemvalue=item.dataset.title;
					 if(itemid=="0"){
						itemvalue = nodeList.otherreason.value;
					 }
					 checkedReasons.push({"id":itemid,"vlaue":itemvalue});
				 }
			 });
            return checkedReasons;
		 },
		precise_round:function(value, decPlaces){// 价格保留两位小数
			var val = value * Math.pow(10, decPlaces);
			var fraction = (Math.round((val-parseInt(val))*10)/10);

			//this line is for consistency with .NET Decimal.Round behavior
			// -342.055 => -342.06
			if(fraction == -0.5) fraction = -0.6;

			val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces);
			return val;
		},
		updateprice:function(){
			nodeList.oprice.innerHTML = ''+custFuncs.precise_round(order_price,2);
			nodeList.tprice.innerHTML = ''+custFuncs.precise_round(order_price,2);
			nodeList.eprice.innerHTML = ''+custFuncs.precise_round(expense_price,2);
			nodeList.rprice.innerHTML = ''+custFuncs.precise_round(return_price,2);
		}
    }

    //-------------一切从这开始--------------
    var init = function(_data) {

        data = _data;
        // 根据数据初始化模块
        // opts["render"]({ "title": data["title"] });

        // 找到所有带有node-name的节点
        nodeList = parseModule(node);
        // 子模块实例化
        initMod();
        // 绑定事件
        bindEvents();


    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};